<?php
namespace app\admin\controller;
use app\common\model\Area;
use think\Validate;
use think\Db;

class AreaController extends BaseController
{
    public function lists()
    {
        return view();
    }
     public function getList($page_size=15)
    {       
        $where = array_filter(input('post.'));
        //print_r($where);
        if (empty($where['parent_id'])) {
            $where['parent_id'] = ['>',0];
        }
        if (!empty($where['name'])) {
            $where['name'] = ['like','%'.$where['name'].'%'];
        }

        $page = max(input('get.page',0),1);
        $page_size = $page_size;
        
        $total = Area::where($where)->count();
        $data = [
            'rows'      => [],
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];
        if ($total == 0) {
            $this->success('无记录','',$data);
        }

        $rows = Area::where($where)->field('parent_id', true)
                                    ->order('parent_id')->page($page, $page_size)->select();
        //echo Area::getlastsql();exit;
        foreach ($rows as $row) {
            $arr = explode(',', $row['name_path']);
            $row['province'] = $arr[0];
            $row['city'] = $arr[1];
            $row['add_time'] = date('Y-m-d H:i',$row['add_time']);
        }

        $data['rows'] = $rows;
        $this->success('成功','',$data);
    }
    public function handle($id=0)
    {
        $data = input('post.');
        //数据验证
        $validate = new Validate([
            ['name','require','地区名称必须'],
        ]);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        //判断是否重复
        if (Area::get(['name'=>$data['name']])) {
            $this->error('地址重复');
        }

        if ($data['parent_id'] ==0) {
            $data['name_path'] = $data['name'];
            $data['level'] = 1;
        } else {
            $parent_path = Db::name('area')->where('id',$data['parent_id'])->value('name_path');
            $data['name_path'] = $parent_path . ',' . $data['name'];
            $data['level'] = Db::name('area')->where('id',$data['parent_id'])->value('level') + 1;
        }
        if ($id>0) {    //编辑
            return Area::update($data,['id'=>$id],true);
        } else {    //新增
            return Area::add($data,true);
        }
    }
    public function getTopList()
    {
        $rows = Db::name('Area')->where('parent_id', 0)->field('parent_id', true)->select();
        $data['rows'] = $rows;
        $this->success('成功','',$data);
    }
    //省份
    public function provinces(){
        $provinces = Db::name('area')->where('level','1')->select();
        $this->success('获取成功','',$provinces);
    }
    
}